/**
 * <p><b>Title:</b> CleanShellThread.java </p>
 *
 * @Package com.wondertek.oes.charge.publish.config
 */
package com.wondertek.poms.pre.listener;

import java.util.Calendar;
import java.util.Set;

import org.springframework.data.redis.core.ZSetOperations.TypedTuple;

import com.wondertek.poms.common.cache.GZIPUtils;
import com.wondertek.poms.common.constant.Constants;

import lombok.extern.slf4j.Slf4j;

/**
 * <p><b>CleanShellThread Description:</b> 清除缓存的线程 </p>
 *
 * @author douzi
 * <b>DATE</b> 2019年9月17日 下午3:27:06
 */
@Slf4j
@Deprecated
public class CleanMamThread implements Runnable {

    private AssetIdDelayPublish delayPublish;

    public CleanMamThread(AssetIdDelayPublish delayPublish) {
        this.delayPublish = delayPublish;
    }

    @Override
    public void run() {
        log.info("===Clean assetId thread run pre minute===");
        while (true) {
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {
                log.error("===Clean assetId thread down===", e);
                Thread.currentThread().interrupt();
            }
            process();
        }
    }

    @SuppressWarnings("unchecked")
    private void process() {
        //由小到大获取所有数据
        Set<TypedTuple<String>> items = delayPublish.redisTemplate.opsForZSet()
                .rangeWithScores(Constants.ACCESSID_DELAY_TOPIC, 0, -1);
        if (items == null || items.isEmpty()) {
            log.info("=====redis缓存中没有等待的任务========");
            return;
        }

        for (int i = 0; i < items.size(); i++) {
			int score = ((TypedTuple<String>) items.toArray()[i]).getScore().intValue();
            String st = ((TypedTuple<String>) items.toArray()[i]).getValue();
            Calendar cal = Calendar.getInstance();
            int nowSecond = (int) (cal.getTimeInMillis() / 1000);
            if (nowSecond >= score) {
                //删除过期的数据，保证其他进程不在处理
                Long num = delayPublish.redisTemplate.opsForZSet()
                        .remove(Constants.ACCESSID_DELAY_TOPIC, st);
                String message = GZIPUtils.uncompress(st);
                if (num != null && num > 0) {
                    log.info("====reids缓存中消费了一个任务st:" + message);
//                    delayPublish.messageSend.send(message);
                    delayPublish.startProcess.slowProcess(st);
                }
            } else {
                log.info("====reids缓存中任务st:" + st + "|未过期");
                // 由于获取数据为由小到大，只要一个未过期，后续都是未过期；
                return;
            }
        }
    }
}
